from django.shortcuts import render, redirect,reverse
from django.views import View

from courses.models import Course
from organization.models import CourseOrg
from user_test.form import RegisterForm
from users.forms import LoginForm, ForgetForm
from users.models import Banner, UserProfile
from users.utils import generate_verify_email_url

from utils.secret import SecretOauth


class IndexView(View):
     # 获取首页
    def get(self, request):
        all_banners = Banner.objects.all()
        courses = Course.objects.all()
        banner_courses = Course.objects.all()
        course_orgs = CourseOrg.objects.all()
        return render(request, 'index.html', {
            'all_banners': all_banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
        })
# 注册页面
class RegisterView(View):
    """用户注册"""
    def get(self, request):
        register_form = RegisterForm()
        return render(request, 'register.html', {'register_form': register_form})
    def post(self,request):
        data = request.POST
        register_form = RegisterForm(data)
        res = register_form.is_valid()  # 验证成功返回True，验证失败返回False

        if res:
            email = register_form.cleaned_data['email']
            username = email
            password = register_form.cleaned_data['password']
            try:
                user = UserProfile.objects.create_user(username=username,email=email, password=password, )
            except Exception as e:
                return render(request, 'register.html')
                # 保持登陆状态
            from django.contrib.auth import login
            login(request, user)

            # 响应注册结果
            response = redirect(reverse('users:index'))
            response.set_cookie('username', username, max_age=24*3600*15)

            return response

        else:
            return render(request, 'register.html', {'register_form': register_form})

# 登陆页面
class LoginView(View):

    def get(self,request):
        return render(request, 'login.html')
    def post(self,request):
        data = request.POST
        login_form = LoginForm(data)
        res = login_form.is_valid()  # 验证成功返回True，验证失败返回False
        if res:
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            from django.contrib.auth import authenticate, login
            user = authenticate(username=username, password=password)
            if user is None:
                return render(request, 'login.html', {'form_errors': login_form.errors})
            # 4.保持登录状态
            login(request, user)
            # 注册时用户名写入到cookie，有效期15天
            response = redirect(reverse('users:index'))

            response.set_cookie('username', username, max_age=3600*24*15)

            return response
        else:
            return render(request, 'login.html', {'form_errors': login_form.errors})

# 忘记密码 暂时有问题
class ForgetPwdView(View):
    def get(self,request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})
    def post(self,request):
        data = request.POST
        forget_form = ForgetForm(data)
        res = forget_form.is_valid()  # 验证成功返回True，验证失败返回False
        if res:
            email = forget_form.cleaned_data['email']
            # try:
            #     user = UserProfile.objects.get(email=email)
            # except Exception as e:
            #     return render(request, 'forgetpwd.html', {'forget_form': forget_form})
            verify_url = generate_verify_email_url(email)
            from celery_tasks.email.tasks import send_verify_email
            send_verify_email.delay(email,verify_url)
#           验证数据成功
            return render(request,'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})

class ResetView(View):
    def get(self,request):
        token = request.GET.get('token')
        try:
            token_dict = SecretOauth().loads(token)
        except:
            return render(request, 'active_fail.html')
        email = token_dict['email']
        try:
            user = UserProfile.objects.get(email=email)
        except:
            return render(request, 'active_fail.html')
        return render(request, 'password_reset.html', {'email': email})